<template>
  <el-menu
    :default-active="active"
    :default-openeds="openeds"
    class="el-menu-vertical-demo"
    :collapse="isCollapse"
    router
  >
    <div v-for="item in menuList">
      <el-sub-menu v-if="item.children" :index="item.path">
        <template #title>
          <i :class="item.meta.icon"></i>
          <span>{{item.meta.title}}</span>
        </template>
        <el-menu-item-group>
          <el-menu-item :index="item.path+subItem.path" v-for="subItem in item.children">{{subItem.meta.title}}</el-menu-item>
        </el-menu-item-group>
      </el-sub-menu>
      <el-menu-item v-else :index="item.path">
        <template #title>
          <i :class="item.meta.icon"></i>
          <span>{{item.meta.title}}</span>
        </template>
      </el-menu-item>
    </div>
  </el-menu>
</template>

<script>
  import {ref, watchEffect , nextTick} from 'vue'
  import {useRouter, useRoute} from 'vue-router'

  export default {
    name: "menu",
    setup() {
      const isCollapse = ref(false)
      let menuList = ref([])
      let active = ref('')
      let openeds = ref([])
      const router = useRouter()
      const route = useRoute()
      const routers = router.options.routes

      if (routers) {
        const itemRouters = JSON.parse(JSON.stringify(routers))
        menuList.value = filterMenu(itemRouters)
        console.log('格式化后的：', menuList.value)
      }

      watchEffect (()=> {
        active.value = route.path
        openeds.value = [route.path]
      })


      function filterMenu(data) {
        let arr = []
        data.forEach((item, index) => {
          if (item.children) {
            let itemArr = filterMenu(item.children)
            if (itemArr && itemArr.length) {
              item.children = itemArr
            }
          }
          if (item.meta.isMenu) {
            arr.push(item)
          }
        })

        return arr
      }

      return {
        isCollapse,
        menuList,
        active,
        openeds
      }
    }
  }
</script>

<style scoped lang="scss">
  .el-menu-vertical-demo {
    height: 100%;
  }
</style>
